package com.aoip.telemetry.telemetry.configureui.business.pipeline.handle.service.impl;

import com.aoip.telemetry.telemetry.configureui.business.pipeline.handle.mapper.PipelineHandleMapper;
import com.aoip.telemetry.telemetry.configureui.business.pipeline.handle.service.PipelineHandleService;
import com.aoip.telemetry.telemetry.core.redis.RedisCache;
import com.aoip.telemetry.telemetry.entity.enums.CacheKeyEnum;
import com.aoip.telemetry.telemetry.entity.pipeline.PipelineHandleEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author chenbai
 * @version 1.0
 * @date 2021/11/25 10:32
 */
@Service
public class PipelineHandleServiceImpl implements PipelineHandleService {
    @Resource
    private PipelineHandleMapper pipelineHandleMapper;
    @Resource
    private RedisCache redisCache;
    @Override
    public List<PipelineHandleEntity> list(PipelineHandleEntity entity) {
        QueryWrapper<PipelineHandleEntity> queryWrapper = new QueryWrapper<>();
        String handleName = entity.getHandleName();
        if (StringUtils.hasText(handleName)) {
            queryWrapper.like(true, "handle_name", handleName);
        }
        return pipelineHandleMapper.selectList(queryWrapper);
    }

    @Override
    public PipelineHandleEntity pipelineHandle(String id) {
        return pipelineHandleMapper.selectById(id);
    }

    @Override
    public int insert(PipelineHandleEntity entity) {
        redisCache.setCacheObject(CacheKeyEnum.PIPELINE_HANDLE + ":" + entity.getId(), entity);
        return pipelineHandleMapper.insert(entity);
    }

    @Override
    public int update(PipelineHandleEntity entity) {
        redisCache.setCacheObject(CacheKeyEnum.PIPELINE_HANDLE + ":" + entity.getId(), entity);
        return pipelineHandleMapper.updateById(entity);
    }

    @Override
    public int initCache() {
        List<PipelineHandleEntity> list = list(new PipelineHandleEntity());
        list.forEach(item -> {
            redisCache.deleteObject(CacheKeyEnum.PIPELINE_HANDLE + ":" + item.getId());
            redisCache.setCacheObject(CacheKeyEnum.PIPELINE_HANDLE + ":" + item.getId(), item);
        });
        return list.size();
    }

    @Override
    public void delete(long[] ids) {
        for (long id : ids) {
            pipelineHandleMapper.deleteById(id);
            redisCache.deleteObject(CacheKeyEnum.PIPELINE_HANDLE + ":" + id);
        }
    }

}
